import { Singleton } from "../utils/Singleton";
import ResourceManager from "./ResourceManager";

export default class ResHelper extends Singleton<ResHelper> {
  public async load<T extends cc.Asset>(
    path: string,
    type: typeof cc.Asset,
    bundleName: string = "game"
  ): Promise<T> {
    try {
      return await ResourceManager.getInstance().loadAsset<T>(
        bundleName,
        path,
        type
      );
    } catch (err) {
      console.error(`[ResHelper] 加载资源失败: ${path}`, err);
      throw err;
    }
  }

  /**
   * 快速设置 Sprite 组件的 SpriteFrame 并自动释放资源
   */
  public async setSpriteFrame(
    sp: cc.Sprite,
    path: string,
    bundleName: string = "textures"
  ): Promise<cc.SpriteFrame> {
    if (!cc.isValid(sp.node)) return;
    const texture = await this.load<cc.Texture2D>(
      path,
      cc.Texture2D,
      bundleName
    );
    if (!texture) return;

    const spriteFrame = new cc.SpriteFrame(texture);
    sp.spriteFrame = spriteFrame;
    return spriteFrame; // ✅ 返回，便于外部管理
  }

  /**
   * 从 TextureAtlas 加载 SpriteFrame
   */
  public async loadSpriteFrameFromAtlas(
    atlasPath: string,
    spriteName: string,
    bundleName: string = "texture"
  ): Promise<cc.SpriteFrame> {
    const atlas = await this.load<cc.SpriteAtlas>(
      atlasPath,
      cc.SpriteAtlas,
      bundleName
    );
    if (!atlas) throw new Error("Failed to load atlas");
    const spriteFrame = atlas.getSpriteFrame(spriteName);
    if (!spriteFrame) throw new Error("Sprite frame not found in atlas");
    return spriteFrame;
  }
}
